package gold.digger;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LCIT1002 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public List<List<String>> groupAnagrams(String[] words) {
            Map<String, List<String>> map = new HashMap<>();
            List<List<String>> res = new ArrayList<>();
            for (String word : words) {
                Map<Character, Integer> wordDict = new TreeMap<>();
                for (int i = 0; i < word.length(); i++) {
                    int count = wordDict.getOrDefault(word.charAt(i), 0);
                    wordDict.put(word.charAt(i), count+1);
                }

                StringBuilder wsb = new StringBuilder();
                for (Character ch : wordDict.keySet()) {
                    wsb.append(String.valueOf(ch)).append(String.valueOf(wordDict.get(ch)));
                }

                if (map.containsKey(wsb.toString())) {
                    map.get(wsb.toString()).add(word);
                } else {
                    List<String> wordAnagramList = new ArrayList<>();
                    wordAnagramList.add(word);
                    map.put(wsb.toString(), wordAnagramList);
                }
            }

            for (List<String> list : map.values()) {
                res.add(list);
            }

            return res;
        }
    }

    public void run() {
        Solution solution = new Solution();
        String[] arr = {"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println(solution.groupAnagrams(arr));
    }

    public static void main(String[] args) throws Exception {
        LCIT1002 an = new LCIT1002();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
